<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessageBox } from 'element-plus'

import { Table } from '@/components/Table'
import {
  adminCsTagAddApi,
  adminCsTagBatchDelApi,
  adminCsTagDelApi,
  adminCsTagEditApi,
  adminCsTagListApi
} from '@/api/cs/tag'
import { adminCsTagGroupListApi } from '@/api/cs/tagGroup'
import { useTable } from '@/hooks/web/useTableTest'
import { TableData } from '@/api/cs/tag/types'
import { ref, unref, reactive } from 'vue'
import Edit from './components/Edit.vue'
import See from './components/See.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'

const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
const iconDel = useIcon({ icon: 'ep:delete' })
const { register, tableObject, methods } = useTable<
  {
    total: number
    list: TableData[]
  },
  any
>({
  getListApi: adminCsTagListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  // {
  //   field: 'tag_id',
  //   label: '主键',
  //   fixed: 'left',
  //   width: 60,
  //   table: {
  //     show: true
  //   },
  //   form: {
  //     show: false
  //   },
  //   detail: {
  //     show: false
  //   }
  // },
  {
    field: 'tag_group_id',
    label: '标签组',
    search: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: adminCsTagGroupListApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择标签组（双击选择）',
        nameField: 'tag_group_name',
        valueField: 'tag_group_id',
        crudSchemas: [
          {
            field: 'tag_group_name',
            label: '标签组名称',
            fixed: 'left',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    },
    form: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: adminCsTagGroupListApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择标签组（双击选择）',
        nameField: 'tag_group_name',
        valueField: 'tag_group_id',
        crudSchemas: [
          {
            field: 'tag_group_name',
            label: '标签组名称',
            fixed: 'left',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    },
    table: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'tag_group_name',
    label: '所属标签组',
    search: {
      show: false
    },
    form: {
      show: false
    }
  },
  {
    field: 'tag_name',
    label: '标签名称',
    search: {
      show: true
    }
  },
  {
    field: 'disp_order',
    label: '排序',
    search: {
      show: false
    },
    form: {
      component: 'InputNumber',
      componentProps: {
        min: 0
      }
    }
  },
  {
    field: 'action',
    width: 300,
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const delLoading = ref(false)

const delData = async () => {
  const { getSelections } = methods
  const selections = await getSelections()
  const ids = selections.map((v) => v.tag_id)
  delLoading.value = true
  ElMessageBox.confirm(t('common.delMessage'), t('common.delWarning'), {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  })
    .then(async () => {
      let res = await adminCsTagBatchDelApi({ ids: ids.join(',') })
        .catch(() => {})
        .finally(() => {
          delLoading.value = false
        })
      if (res) {
        getList()
      }
    })
    .catch(() => {})
}

const actionType = ref('')

const action = async (type: string, row: TableData = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {}
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm('确定要删除这个角色吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiDel(row.tag_id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    default:
      console.log('未知类型')
  }
}

const apiDel = async (tag_id) => {
  let delRes = await adminCsTagDelApi({ tag_id: tag_id })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (delRes) {
    getList()
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()

const loading = ref(false)

const save = async () => {
  const edit = unref(editRef)
  switch (actionType.value) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as TableData
          let res = await adminCsTagEditApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })

      break
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as TableData
          let res = await adminCsTagAddApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
      <ElButton :loading="delLoading" type="danger" @click="delData()"> 批量删除 </ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton type="primary" :icon="iconEdit" @click="action('edit', row)" title="编辑">
          编辑
        </ElButton>
        <ElButton type="success" :icon="iconSee" @click="action('see', row)" title="详情">
          详情
        </ElButton>
        <ElButton type="danger" :icon="iconDel" @click="action('del', row)" title="删除">
          删除
        </ElButton>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit
      v-if="actionType == 'edit' || actionType == 'add'"
      ref="editRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />

    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="loading" @click="save()">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
